<template>
   <div class="app-container">
      <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
         <el-form-item label="模板名称" prop="postCode">
            <el-input v-model="queryParams.templateName" placeholder="请输入模板名称" clearable style="width: 200px"
               @keyup.enter="handleQuery" />
         </el-form-item>
         <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
         </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8" style="margin-left: 1350px;">
         <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd"
               v-hasPermi="['system:post:add']">新增</el-button>
         </el-col>
      </el-row>

      <el-table v-loading="loading" :data="postList" @selection-change="handleSelectionChange">
         <el-table-column label="模板ID" align="center" prop="id" />
         <el-table-column label="模板名称" width="200" align="center" prop="templateName" />
         <el-table-column label="是否启用" align="center" prop="isEnable">
            <!-- 判断是否启用 ，启用展示绿色 禁用展示红色-->
            <template #default="scope">
               <el-tag :type="scope.row.isEnable === '1' ? 'success' : 'danger'">
                  {{ scope.row.isEnable === '1' ? '启用' : '禁用' }}
               </el-tag>
            </template>
         </el-table-column>
         <!-- 附件名称 支持点击名称下载 -->
         <el-table-column label="附件名称" width="280" align="center" prop="attachmentName">
            <template #default="scope">
               <el-link :underline="false" type="primary" @click="handleDownload(scope.row.id, 1, scope.row.attachmentName)">
                  {{ scope.row.attachmentName }}
               </el-link>
            </template>
         </el-table-column>
         
         <el-table-column width="300" label="字段注释附件" align="center" prop="fieldAttachmentName">
            <template #default="scope">
               <el-link :underline="false" type="primary" @click="handleDownload(scope.row.id, 2, scope.row.fieldAttachmentName)">
                  {{ scope.row.fieldAttachmentName }}
               </el-link>
            </template>
         </el-table-column>
         
         <!-- 创建人  -->
         <el-table-column label="创建人" align="center" prop="createBy" />
         <el-table-column label="创建时间" align="center" prop="createTime" width="180">
            <template #default="scope">
               <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
         </el-table-column>
         <!-- 修改人  -->
         <el-table-column label="修改人" align="center" prop="updateBy" />
         <el-table-column label="修改时间" align="center" prop="updateTime" width="180">
            <template #default="scope">
               <span>{{ parseTime(scope.row.updateTime) }}</span>
            </template>
         </el-table-column>
         <el-table-column label="操作" width="200" align="center" class-name="small-padding fixed-width">
            <template #default="scope">
               <!-- 根据isEnable字段展示按钮 等于1 启用时 展示 修改 删除按钮，等0 禁用时展示启用按钮 -->
               <div v-if="scope.row.isEnable === '1'">
                  <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                     v-hasPermi="['system:post:edit']">修改</el-button>
                  <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['system:post:remove']">删除</el-button>
                  <el-button link type="primary" icon="Edit" @click="handleEnable(scope.row)"
                     v-hasPermi="['system:post:edit']">禁用</el-button>
               </div>
               <div v-else>
                  <el-button link type="primary" icon="Edit" @click="handleEnable(scope.row)"
                     v-hasPermi="['system:post:edit']">启用</el-button>
               </div>
            </template>
         </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
         v-model:limit="queryParams.pageSize" @pagination="getList" />

      <!-- 添加或修改对话框 -->
      <el-dialog :title="title" v-model="open" width="900px" append-to-body>
         <el-form ref="postRef" :model="form" :rules="rules" label-width="110px">
            <el-form-item label="模板名称" prop="templateName">
               <el-input v-model="form.templateName" placeholder="请输入模板名称" />
            </el-form-item>
            <!-- 新增的数据源选择项 -->
            <el-form-item label="数据源" prop="dataSourceId">
               <el-select v-model="form.dataSourceId" placeholder="请选择数据源" style="width: 100%" clearable filterable>
                  <el-option v-for="item in dataSourceOptions" :key="item.id" :label="item.dataSourceName"
                     :value="item.id" />
               </el-select>
            </el-form-item>

            <!-- <el-form-item label="是否地级市" prop="isCity">
               <el-select v-model="form.isCity" placeholder="请选择" style="width: 100%" clearable>
                  <el-option label="是" value="1" />
                  <el-option label="否" value="0" />
               </el-select>
            </el-form-item>
            <el-form-item label="是否需要变量" prop="isVariable">
               <el-select v-model="form.isVariable" placeholder="请选择" style="width: 100%"
                  @change="handleIsVariableChange" clearable>
                  <el-option label="是" value="1" />
                  <el-option label="否" value="0" />
               </el-select>
            </el-form-item> -->

            <!-- 动态显示/隐藏取数起止时间 -->
            <div v-if="form.isVariable === '1'">
               <el-form-item label="取数时间区间" prop="qsDateTime">
                  <el-date-picker v-model="form.qsDateTime" type="datetimerange" range-separator="至"
                     start-placeholder="开始日期" end-placeholder="结束日期">
                  </el-date-picker>
               </el-form-item>
            </div>

            <el-form-item label="SQL内容" prop="execSql">
              <el-tooltip :content="form.tempTableName">
                <span>查看临时表名</span>
              </el-tooltip>
               <el-input v-model="form.execSql" :rows="6" type="textarea" placeholder="请输入SQL" />

            </el-form-item>

            <el-form-item label="预设变量" prop="variables">
               <div class="variables-container">
                  <el-button type="primary" link @click="addVariable" style="margin-bottom: 10px;">
                     <el-icon><Plus /></el-icon>新增变量
                  </el-button>
                  
                  <div v-for="(variable, index) in form.variables" :key="index" class="variable-item">
                     <el-row :gutter="10" style="margin-bottom: 10px;">
                        <el-col :span="6">
                           <el-form-item 
                           :prop="`variables.${index}.fieldName`"
                           :rules="[
                              { required: true, message: '请输入字段名', trigger: 'blur' }
                           ]">
                              <el-input v-model="variable.fieldName" placeholder="变量字段名" />
                           </el-form-item>
                        </el-col>
                        <el-col :span="6">
                           <el-form-item 
                           :prop="`variables.${index}.fieldType`"
                           :rules="[
                              { required: true, message: '请选择字段类型', trigger: 'change' }
                           ]">
                              <el-select v-model="variable.fieldType" placeholder="字段类型" style="width: 100%">
                                 <el-option label="字符串" value="string" />
                                 <el-option label="数字" value="number" />
                                 <el-option label="日期" value="date" />
                              </el-select>
                           </el-form-item>
                        </el-col>
                        <el-col :span="6">
                           <el-form-item 
                           :prop="`variables.${index}.required`"
                           :rules="[
                              { required: true, message: '请选择是否必填', trigger: 'change' }
                           ]">
                              <el-select v-model="variable.required" placeholder="是否必填" style="width: 100%">
                                 <el-option label="是" value="1" />
                                 <el-option label="否" value="0" />
                              </el-select>
                           </el-form-item>
                        </el-col>
                        <!-- 描述字段不需要校验 -->
                        <el-col :span="18" style="margin-top: 20px;">
                           <!-- 判断id是否为空 id为则显示 -->
                           <el-form-item v-if="variable.variableId" :prop="`variables.${index}.variableRemark`">
                              <el-input v-model="variable.variableRemark" placeholder="字段描述" />
                           </el-form-item>
                           <el-form-item v-else :prop="`variables.${index}.remark`">
                              <el-input v-model="variable.remark" placeholder="字段描述" />
                           </el-form-item>
                        </el-col>
                        <el-col :span="1" style="margin-top: 20px;">
                           <el-button type="danger" link @click="removeVariable(index)">
                              <el-icon><Delete /></el-icon>
                           </el-button>
                        </el-col>
                     </el-row>
                  </div>
               </div>
            </el-form-item>

            <el-form-item label="字段注释附件" prop="annotationFileList">
               <el-upload
                  style="width: 800px;"
                  :limit="1"
                  accept=".txt"
                  :auto-upload="false"
                  drag
                  multiple
                  @change="handleTableTemplateChange"
                  @remove="handleTableTemplateRemove"
                  :file-list="form.annotationFileList">
                  <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                  <template #tip>
                        <div class="el-upload__tip text-center">
                           <span>仅允许导入.txt格式文件。</span>
                           <el-button link type="primary" @click="downloadTableTemplate">下载模板</el-button>
                        </div>
                  </template>
               </el-upload>
            </el-form-item>

<!--            <el-form-item label="临时表数据" prop="fileList">-->
<!--               <el-upload style="width: 800px;" :limit="1" accept=".txt" :auto-upload="false" drag multiple-->
<!--                  @change="handleFileChange"-->
<!--                  @remove="handleFileRemove"-->
<!--                  :file-list="form.fileList">-->
<!--                  <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>-->
<!--                  <template #tip>-->
<!--                     <div class="el-upload__tip text-center">-->
<!--                        <span>仅允许导入.txt格式文件。</span>-->
<!--                        <el-button link type="primary" @click="downloadTempTableTemplate">下载模板</el-button>-->
<!--                     </div>-->
<!--                  </template>-->
<!--                  &lt;!&ndash; 当tempTableName不为空的时候 显示临时表名 字体显示成红色 &ndash;&gt;-->
<!--                  <div v-if="form.tempTableName" style="color: red;" class="temp-table-name">-->
<!--                     临时表名：{{ form.tempTableName }}-->
<!--                  </div>-->
<!--               </el-upload>-->
<!--            </el-form-item>-->

            <el-form-item label="备注" prop="remark">
               <el-input v-model="form.remark" :rows="5" type="textarea" placeholder="请输入内容" />
            </el-form-item>
         </el-form>

         <template #footer>
            <div class="dialog-footer">
               <el-button @click="cancel">取 消</el-button>
               <el-button type="primary" @click="submitForm" :loading="submitLoading">确 定</el-button>
            </div>
         </template>
      </el-dialog>
   </div>
</template>

<script setup name="Post">
import {
   listTemplate, addTemplate, updateTemplate, delTemplate,
   enableOrDisable, getTemplate
} from "@/api/tempcfg/templatecfg/templatecfg";
import {
    listAll
  } from "@/api/tempcfg/datasource/datasources";
const { proxy } = getCurrentInstance();
const postList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(2);
const title = ref("");

const data = reactive({
   form: {
      id: undefined,
      templateName: undefined,
      dataSourceId: undefined,
      dataSourceName: undefined,
      isCity: '1',
      isVariable: '0',
      qsDateTime: [],
      fileList: [],
      execSql: undefined,
      remark: undefined,
      variables: [], // 预设变量列表
      annotationFileList: [], // 字段注释文件
   },
   queryParams: {
      pageNum: 1,
      pageSize: 10,
      postCode: undefined,
      postName: undefined,
      status: undefined
   },
   rules: {
      templateName: [{ required: true, message: "模板名称不能为空", trigger: "blur" }],
      dataSourceId: [{ required: true, message: "数据源不能为空", trigger: "change" }],
      isCity: [{ required: true, message: "是否地级市不能为空", trigger: "change" }],
      isVariable: [{ required: true, message: "是否需要变量不能为空", trigger: "change" }],
      // isVariable 为 1 时，qsDateTime 不能为空
      qsDateTime: [{ required: true, message: "取数时间区间不能为空", trigger: "change"}],
      execSql: [{ required: true, message: "SQL内容不能为空", trigger: "blur" }],
   },
   submitLoading: false // 新增提交loading状态
});

const { queryParams, form, rules, submitLoading} = toRefs(data);

// 在script部分添加假数据
const dataSourceOptions = ref([]);

function getDataSourceOptions() {
   listAll().then(response => {
      dataSourceOptions.value = response.data;
   });
}


/** 查询岗位列表 */
function getList() {
   loading.value = true;
   listTemplate(queryParams.value).then(response => {
      postList.value = response.rows;
      total.value = response.total;
      loading.value = false;
   });
}


/** 取消按钮 */
function cancel() {
   open.value = false;
   reset();
}

/** 表单重置 */
function reset() {
   form.value = {
      id: undefined,
      templateName: undefined,
      templateCode: undefined,
      execSql: undefined,
      remark: undefined,
      fileList: [],
      variables: [], // 添加variables字段
      annotationFileList: [], // 添加annotationFileList字段
   };
   proxy.resetForm("postRef");
}

/** 搜索按钮操作 */
function handleQuery() {
   queryParams.value.pageNum = 1;
   getList();
}

/** 重置按钮操作 */
function resetQuery() {
   proxy.resetForm("queryRef");
   queryParams.value.templateName = undefined;
   handleQuery();
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
   ids.value = selection.map(item => item.postId);
   single.value = selection.length != 1;
   multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
   reset();
   open.value = true;
   title.value = "新增模板";
  // 使用格式化函数生成临时表名
  form.value.tempTableName = "temp_" + formatTimestamp(Date.now());
  getDataSourceOptions();
}

/** 修改按钮操作 */
function handleUpdate(row) {
   reset();
   title.value = "修改模板";
   getDataSourceOptions();
   getTemplate(row.id).then(response => {
      let data = response.data;
      form.value = data;
      // 判断是否有附件
     
      if (data.attachmentName) {
         form.value.fileList = [{ name: data.attachmentName, url: data.attachmentPath }];
      } else {
         form.value.fileList = [];
      }
      if (data.fieldAttachmentName) {
         form.value.annotationFileList = [{ name: data.fieldAttachmentName, url: data.fieldAttachmentPath }];
      } else {
         form.value.annotationFileList = [];
      }

      if (data.startTime && data.endTime) {
         form.value.isVariable = "1";
      } else {
         form.value.isVariable = "0";
      }
      open.value = true; 
   })
}

/** 提交按钮 */
function submitForm() {
   proxy.$refs["postRef"].validate(valid => {
      submitLoading.value = true;
      if (valid) {
         // 使用 find 方法查找与 form.value.dataSourceId 匹配的选项
         const selectedOption = dataSourceOptions.value.find(item => item.id === form.value.dataSourceId);
         if (!selectedOption) {
            proxy.$modal.msgError("请选择数据源");
            submitLoading.value = false;
            return;
         }
         form.value.dataSourceName = selectedOption.label;
         if (form.value.isVariable === "1") {
            if (!form.value.qsDateTime) {
               proxy.$modal.msgError("请选择取数时间区间");
               submitLoading.value = false;
               return;
            }
            form.value.startTime = form.value.qsDateTime[0];
            form.value.endTime = form.value.qsDateTime[1];
         }
         // 文件
         if (form.value.fileList.length > 0) {
            form.value.attachment = form.value.fileList[0].raw;
         }
         if (form.value.annotationFileList.length > 0) {
            form.value.fieldAttachment = form.value.annotationFileList[0].raw;
         }

         if (form.value.id != undefined) {
            updateTemplate(form.value).then(response => {
               proxy.$modal.msgSuccess("修改成功");
               open.value = false;
               getList();
            }).catch(error => {
               submitLoading.value = false;
            });
         } else {
            addTemplate(form.value).then(response => {
               proxy.$modal.msgSuccess("新增成功");
               open.value = false;
               getList();
            }).catch(error => {
               submitLoading.value = false;
            });
         }
      }
      submitLoading.value = false;
   });
}

// 添加格式化函数
const formatTimestamp = (timestamp) => {
    const date = new Date(timestamp);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');
    const milliseconds = String(date.getMilliseconds()).padStart(3, '0').slice(0, 2);
    return `${year}${month}${day}${hours}${minutes}${seconds}${milliseconds}`;
};

// ... existing code ...

function handleFileChange(file, fileList) {
   // 检查文件扩展名
  const allowedExtensions = ['.txt'];
  const extension = file.name.substring(file.name.lastIndexOf('.')).toLowerCase();
  
  if (!allowedExtensions.includes(extension)) {
    proxy.$modal.msgError('只允许上传.txt格式文件');
    form.value.fileList = [];
    return false;
  } else {
      // 更新 form.fileList 的值
      form.value.fileList = fileList;
      // 生成一个临时表名
      if (fileList.length > 0) {
         // 使用格式化函数生成临时表名
         form.value.tempTableName = "temp_" + formatTimestamp(Date.now()); 
      }
  }
}

function handleFileRemove(file, fileList) {
   form.value.fileList = fileList;
   // 文件删除后清空临时表名
   form.value.tempTableName = undefined; 
}



/** 删除按钮操作 */
function handleDelete(row) {
   proxy.$modal.confirm('是否确认删除模板名称为"' + row.templateName + '"的数据项？').then(function () {
      return delTemplate(row.id);
   }).then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
   }).catch((e) => {
      console.log(e);
   });
}

/** 启/禁用按钮操作 */
function handleEnable(row) {
   let statusName = row.isEnable == "1" ? "禁用" : "启用";
   let status = row.isEnable == "1" ? "0" : "1";
   proxy.$modal.confirm('是否确认' + statusName + '模板名称为"' + row.templateName + '"的数据项？').then(function () {
      return enableOrDisable(row.id, status);
   }).then(() => {
      getList();
      proxy.$modal.msgSuccess(statusName + "成功");
   }).catch((e) => {
      console.log(e);
   });
}

/** 导出按钮操作 */
function handleExport() {
   proxy.download("system/post/export", {
      ...queryParams.value
   }, `post_${new Date().getTime()}.xlsx`);
}

getList();

// 添加变量
const addVariable = () => {
   form.value.variables.push({
      fieldName: undefined,
      fieldType: undefined,
      required: undefined,
      remark: undefined
   });
};

// 删除变量
const removeVariable = (index) => {
   form.value.variables.splice(index, 1);
};


function handleTableTemplateChange(file, fileList) {
   // 检查文件扩展名
   const allowedExtensions = ['.txt'];
   const extension = file.name.substring(file.name.lastIndexOf('.')).toLowerCase();

   if (!allowedExtensions.includes(extension)) {
      proxy.$modal.msgError('只允许上传.txt格式文件');
      form.value.annotationFileList = [];
      return false;
   } else {
    // 如果上传了新文件，替换旧文件
    form.value.annotationFileList = [file];
   }
}


function handleTableTemplateRemove(file, fileList) {
   form.value.annotationFileList = fileList;
}


function downloadTableTemplate() {
   proxy.$download.file("/data/template/cfg/download/filed/template", "table_filed_template.txt");
}

function handleDownload(id, type, fileName) {
   proxy.$download.file("/data/template/cfg/download/"+id+"/" + type, fileName);
}

function downloadTempTableTemplate() {
   proxy.$download.file("/data/template/cfg/temp/table/download", "temp_table_filed_data_template.txt");
}

</script>

<style scoped>
.hint-text {
   color: #999;
   font-size: 12px;
   margin-top: 0px;
   margin-left: 0px;
   line-height: 1.5;
}
</style>